<template>
  <t-form
    :data="formData"
    :rules="formRules"
    ref="formRef"
    label-align="right"
    colon
    labelWidth="90px"
  >
    <t-form-item name="name" label="项目名称">
      <t-input v-model="formData.name" placeholder=""></t-input>
    </t-form-item>
    <t-form-item name="introduction" label="项目简介">
      <t-textarea
        v-model="formData.introduction"
        :autosize="{ minRows: 6, maxRows: 8 }"
      ></t-textarea>
    </t-form-item>
    <t-form-item name="attachment" label="任务书">
      <div>
        <div
          style="height: 32px; line-height: 32px; margin-bottom: 4px"
          v-if="formData.attachmentId"
        >
          <t-link theme="default" @click="downloadAttachment">
            {{ formData.attachmentName || formData.attachmentId }}
          </t-link>
          <t-popconfirm
            theme="warning"
            placement="right"
            :on-confirm="removeFile"
          >
            <template #content>
              <div class="title">确认删除任务书吗？</div>
              <div class="describe">删除后请点击下方按钮保存信息</div>
            </template>
            <t-button
              theme="default"
              variant="text"
              shape="square"
              style="vertical-align: top; margin-left: 8px"
            >
              <template #icon>
                <delete-icon></delete-icon>
              </template>
            </t-button>
          </t-popconfirm>
        </div>
        <t-upload
          theme="custom"
          :request-method="uploadFile"
          :tips="
            props.init
              ? '上传或删除任务书后，请点击下方按钮保存信息'
              : undefined
          "
        >
          <t-button theme="default" variant="outline" :loading="uploadLoading">
            <template #icon>
              <upload-icon></upload-icon>
            </template>
            {{ formData.attachmentId ? '更换任务书' : '上传任务书' }}
          </t-button>
        </t-upload>
      </div>
    </t-form-item>
  </t-form>
</template>

<script setup lang="ts">
import { uploadInstruction } from '@/apis/project'
import { download } from '@/apis/file'
import { saveDownload } from '@/utils/download'
import type {
  UploadFile,
  RequestMethodResponse,
  FormRules,
  FormValidateResult,
} from 'tdesign-vue-next'
import { reactive, ref, watch } from 'vue'
import { UploadIcon, DeleteIcon } from 'tdesign-icons-vue-next'

export interface FormData {
  name: string
  introduction: string
  attachmentId?: string
  attachmentName?: string
}

interface Props {
  init?: FormData
}

const props = defineProps<Props>()

const formData = reactive<FormData>({
  name: props.init?.name || '',
  introduction: props.init?.introduction || '',
  attachmentId: props.init?.attachmentId || undefined,
  attachmentName: props.init?.attachmentName || undefined,
})

watch(props, () => {
  if (props.init) {
    formData.name = props.init.name
    formData.introduction = props.init.introduction
    formData.attachmentId = props.init.attachmentId
    formData.attachmentName = props.init.attachmentName
  }
})

const formRules: FormRules<FormData> = {
  name: [{ required: true, message: '请输入项目名称' }],
  introduction: [{ required: true, message: '请输入项目简介' }],
}

const uploadLoading = ref(false)
const uploadFile = (
  file: UploadFile | UploadFile[]
): Promise<RequestMethodResponse> => {
  return new Promise((resolve, reject) => {
    uploadLoading.value = true
    uploadInstruction(file as UploadFile)
      .then((res) => {
        formData.attachmentId = res.payload.id
        formData.attachmentName = res.payload.filename
        resolve({
          status: 'success',
          response: {
            url: 'unknown',
          },
        })
      })
      .catch((err) => {
        reject({
          status: 'fail',
          response: err,
        })
      })
      .finally(() => {
        uploadLoading.value = false
      })
  })
}
const removeFile = () => {
  formData.attachmentId = ''
  formData.attachmentName = ''
}

const downloadAttachment = () => {
  download(formData.attachmentId!).then((res) => {
    saveDownload(
      res,
      formData.attachmentName || formData.attachmentId || 'attachment'
    )
  })
}

const formRef = ref()
const validate = (): Promise<FormData> => {
  return new Promise((resolve, reject) => {
    formRef.value
      .validate()
      .then((res: FormValidateResult<FormData>) => {
        if (res === true) {
          resolve(formData)
        } else {
          reject()
        }
      })
      .catch(() => {
        reject()
      })
  })
}
const reset = () => {
  formRef.value.reset()
}
defineExpose({ validate, reset })
</script>

<style scoped lang="less">
:deep(.t-upload) {
  width: 100%;
}
:deep(.t-upload__dragger) {
  width: 100%;
}
:deep(.t-upload__single-input-preview) {
  max-width: 100%;
}
.title {
  font-weight: 500;
  font-size: 14px;
}
.describe {
  margin-top: 8px;
  font-size: 12px;
  color: var(--td-text-color-secondary);
}
</style>
